//
//  AppDelegate.m
//  Alps
//
//  Created by dllo on 16/6/6.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "AppDelegate.h"
#import "ALPS_LeftLockerController.h"
#import "ALPS_MainController.h"
#import "ALPS_ClassifyController.h"
#import "ALPS_RadioController.h"
#import "ALPS_AnnouncementController.h"

#import "WMPageController.h"

// 悬浮窗
#import "UIButton+NMCategory.h"
#import "ALPS_TSearchViewController.h"

// 播放界面
#import "ALPS_PlayerMainViewController.h"
#import "ALPS_PlayNavigationController.h"
#import "Reachability.h"
#import "MBProgressHUD.h"

@interface AppDelegate ()
@property (nonatomic, strong) ALPS_LeftLockerController *leftVC;
@property (nonatomic, strong) WMPageController *mainVC;
@property (nonatomic, retain) Reachability *conn;
// 夜间模式
@property (nonatomic, strong) UIView *blackView;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];   //设置通用背景颜色
    [self.window makeKeyAndVisible];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetWorkingState) name:kReachabilityChangedNotification object:nil];
    
    _conn = [Reachability reachabilityForInternetConnection];
    //开始监听
    [_conn startNotifier];
    [self checkNetWorkingState];
    
    //导航条
    self.mainVC = [self getPages];
    self.mainVC.menuHeight = 35;
    self.mainVC.menuViewStyle = WMMenuViewStyleLine;
    self.mainVC.menuBGColor = [UIColor whiteColor];
    self.mainVC.titleColorSelected = [UIColor colorWithRed:1.00 green:0.46 blue:0.40 alpha:1.00];
    self.mainVC.menuItemWidth = 40;
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:self.mainVC];
    self.leftVC = [[ALPS_LeftLockerController alloc] init];

    self.LeftSlideVC = [[LeftSlideViewController alloc] initWithLeftView:self.leftVC andMainView:nav];
    self.pNAV = [[ALPS_PlayNavigationController alloc] initWithRootViewController:self.LeftSlideVC];
    self.pNAV.navigationBar.hidden = YES;
    self.window.rootViewController = _pNAV;
    
    //打开音频会话:
    AVAudioSession *session = [[AVAudioSession alloc] init];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];


    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:0.474 green:0.483 blue:0.910 alpha:1.000]];
    [[UINavigationBar appearance] setTranslucent:NO];
    [[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
    

    self.mainVC.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"LeftBarButtonMenu"] imageWithRenderingMode:1] style:UIBarButtonItemStylePlain target:self action:@selector(didClickedMenuBarButton:)];
    
    self.mainVC.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Find"] imageWithRenderingMode:1] style:UIBarButtonItemStylePlain target:self action:@selector(didClickedFindBarButton:)];
    
    
    
    self.blackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreeWidth, ScreeHeight)];
//    [self.mainVC.navigationController.navigationBar addSubview:_blackView];
    [self.window addSubview:_blackView];
    _blackView.backgroundColor = [UIColor blackColor];
    _blackView.userInteractionEnabled = NO;
    _blackView.alpha = 0;
    #warning (2)通知第二步:
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(NightMode) name:@"夜间模式" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didClickedOpenRightVc) name:@"夜间模式" object:nil];

#warning (2)通知第二步:为想接收名字为"村口大喇叭"的通知中心所发送的信息的视图控制器添加注册(注册成为该村村民,能听到大喇叭信息了)
    //为当前视图控制器添加注册通知中心:
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didClickedOpenRightVc) name:@"推出收藏夹" object:nil];
    
    return YES;
    
}

- (void)NightMode
{
    if (self.blackView.alpha == 0)
    {
        [UIView animateWithDuration:0.3 animations:^{
            self.blackView.alpha = 0.4;
        }];
        return;
    }
    else
    {
        [UIView animateWithDuration:0.3 animations:^{
            self.blackView.backgroundColor = [UIColor blackColor];
            self.blackView.alpha = 0;
        }];
        return;
    }
}





- (void)didClickedOpenRightVc
{
    [self.LeftSlideVC closeLeftView];
}

- (void)checkNetWorkingState
{
    
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    _conn = [Reachability reachabilityForInternetConnection];
    
    if ([wifi currentReachabilityStatus] != NotReachable) {
        NSLog(@"wifi");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [MBProgressHUD showSuccess:@"当前为wifi"];
        });
        
        
    }
    else if ([_conn currentReachabilityStatus] != NotReachable){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [MBProgressHUD showSuccess:@"当前为移动网络"];
        });
        
    }else
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [MBProgressHUD showSuccess:@"你的网络不给力呀"];
        });
        
    }
}

- (void)didClickedMenuBarButton:(UIBarButtonItem *)button
{
    [self.LeftSlideVC openLeftView];
}

- (void)didClickedFindBarButton:(UIBarButtonItem *)button
{
    ALPS_TSearchViewController *TSVC = [[ALPS_TSearchViewController alloc] init];
    [self.mainVC.navigationController pushViewController:TSVC animated:YES];
}


- (WMPageController *)getPages
{
    NSArray *controllerArray = [NSArray arrayWithObjects:[ALPS_MainController class], [ALPS_ClassifyController class], [ALPS_RadioController class], [ALPS_AnnouncementController class], nil];
    NSArray *titleArray = [NSArray arrayWithObjects:@"推荐", @"分类", @"广播", @"榜单", nil];
    WMPageController *mainVC = [[WMPageController alloc] initWithViewControllerClasses:controllerArray andTheirTitles:titleArray];
    
    
    return mainVC;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.ssWang.Alps" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Alps" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Alps.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
